<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="卡号/手机号" prop="cardNo">
        <el-input v-model="queryParams.cardNo" placeholder="请输入卡号/手机号" clearable style="width: 240px"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-download" size="mini" @click="exportData">导出</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:role:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="id" prop="id" width="200" />
      <el-table-column label="编号" prop="cardNo" />
      <el-table-column label="手机号" prop="phone" width="120" />
      <el-table-column label="实体卡类型" prop="cardType" width="120">
        <template slot-scope="scope">
          {{ cardTypeMap[scope.row.cardType] }}
        </template>
      </el-table-column>
      <el-table-column label="余额(元)" prop="balance" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.balance / 100 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="cardStatus">
        <template slot-scope="scope">
          <span>{{ cardStatusMap[scope.row.cardStatus] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" prop="remarks" />
      <el-table-column label="有效期类型" prop="expireType" width="100">
        <template slot-scope="scope">
          {{ expireTypeMap[scope.row.expireType] }}
        </template>
      </el-table-column>
      <el-table-column label="有效期" prop="expireTime" width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="200">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <div>
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:role:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:role:remove']">删除</el-button>
          </div>
          <div>
            <el-button size="mini" type="text" icon="el-icon-s-finance"
              @click="showRechargeModal(scope.row)">充值</el-button>
            <el-button size="mini" type="text" icon="el-icon-turn-off"
              @click="showStatusModal(scope.row)">状态变更</el-button>
          </div>
          <div>
            <el-button size="mini" type="text" icon="el-icon-s-order"
              @click="showRechargeRecordsModal(scope.row)">充值记录</el-button>
            <el-button size="mini" type="text" icon="el-icon-s-order"
              @click="showConsumeRecordsModal(scope.row)">消费记录</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" :page-sizes="[10, 20, 30, 50, 500, 1000]" />

    <!-- 新增/修改实体卡 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <!-- 卡类型 -->
        <el-form-item label="卡类型" prop="cardType">
          <el-select style="width: 100%" v-model="form.cardType" placeholder="请选择卡类型">
            <el-option label="消费卡" value="MONEY"></el-option>
            <!-- <el-option label="次数卡" value="NUMBER"></el-option> -->
          </el-select>
        </el-form-item>
        <!-- 有效期类型 -->
        <el-form-item label="有效期类型" prop="expireType">
          <el-select style="width: 100%" v-model="form.expireType" placeholder="请选择有效期类型">
            <el-option label="长期有效" value="LONG_TERM"></el-option>
            <el-option label="短期有效" value="SHORT_TERM"></el-option>
          </el-select>
        </el-form-item>
        <!-- 有效期类型 -->
        <el-form-item v-if="form.expireType === 'SHORT_TERM'" label="有效期" prop="expireTime">
          <el-date-picker style="width: 100%" v-model="form.expireTime" type="date" placeholder="选择有效期">
          </el-date-picker>
        </el-form-item>
        <!-- 是否跨站点使用 -->
        <el-form-item label="是否跨站点使用" required>
          <el-switch v-model="form.crossSite" active-value="ON" inactive-value="OFF"></el-switch>
        </el-form-item>
        <!-- 使用站点 -->
        <el-form-item v-if="form.crossSite === 'ON'" label="使用站点" required>
          <el-transfer filterable v-model="form.siteIds" :data="siteList" :titles="['全部站点', '使用站点']">
          </el-transfer>
        </el-form-item>
        <!-- 编号 -->
        <el-form-item label="编号">
          <el-input v-model="form.cardNo" placeholder="请输入编号" />
        </el-form-item>
        <!-- 余额 -->
        <el-form-item label="余额(元)">
          <el-input v-model="form.balance" placeholder="请输入余额" />
        </el-form-item>
        <!-- 备注 -->
        <el-form-item label="备注">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 充值 弹窗 -->
    <el-dialog title="充值" :visible.sync="rechargeVisible" width="400px">
      <el-form ref="rechargeForm" :model="rechargeForm" :rules="rechargeRules" label-width="120px">
        <el-form-item label="金额(元)" prop="balance">
          <el-input v-model="rechargeForm.balance" placeholder="请输入金额(元)" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRechargeForm">确 定</el-button>
        <el-button @click="rechargeVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 状态修改 弹窗 -->
    <el-dialog title="状态修改" :visible.sync="statusVisible" width="400px">
      <el-form ref="statusForm" :model="statusForm" :rules="statusRules" label-width="60px">
        <el-form-item label="状态" prop="cardStatus">
          <el-select style="width: 100%" v-model="statusForm.cardStatus" placeholder="请选择卡状态">
            <el-option label="已激活" value="ACTIVATED"></el-option>
            <el-option label="待激活" value="TO_BE_ACTIVATED"></el-option>
            <el-option label="已挂失" value="LOSS"></el-option>
            <el-option label="已注销" value="LOGOUT"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStatusForm">确 定</el-button>
        <el-button @click="statusVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 充值记录 弹窗 -->
    <el-dialog title="充值记录" :visible.sync="rechargeRecordsVisible" width="950px">
      <el-table v-loading="rechargeRecordsLoading" :data="rechargeRecordsList">
        <el-table-column label="id" prop="id" width="200" />
        <el-table-column label="编号" prop="cardNo" />
        <el-table-column label="数额" prop="amount">
          <template slot-scope="scope">
            {{ scope.row.amount / 100 }}元
          </template>
        </el-table-column>
        <el-table-column label="充值类型" prop="optType">
          <template slot-scope="scope">
            {{ optType[scope.row.optType] }}
          </template>
        </el-table-column>
        <el-table-column label="订单号" prop="orderNo" width="200" />
        <el-table-column label="创建时间" prop="createTime" width="200" />
      </el-table>

      <pagination v-show="rechargeRecordsTotal > 0" :total="rechargeRecordsTotal"
        :page.sync="rechargeRecordsParams.pageNum" :limit.sync="rechargeRecordsParams.pageSize"
        @pagination="getRechargeRecordsList" :page-sizes="[10, 20, 30, 50, 500, 1000]" />
    </el-dialog>

    <!-- 消费记录 弹窗 -->
    <el-dialog title="消费记录" :visible.sync="consumeRecordsVisible" width="950px">
      <el-table v-loading="consumeRecordsLoading" :data="consumeRecordsList">
        <el-table-column label="id" prop="id" width="200" />
        <el-table-column label="编号" prop="cardNo" />
        <el-table-column label="数额" prop="amount">
          <template slot-scope="scope">
            {{ scope.row.amount / 100 }}元
          </template>
        </el-table-column>
        <el-table-column label="消费类型" prop="optType">
          <template slot-scope="scope">
            {{ scope.row.optType }}
          </template>
        </el-table-column>
        <el-table-column label="订单号" prop="orderNo" width="200" />
        <el-table-column label="创建时间" prop="createTime" width="200" />
      </el-table>

      <pagination v-show="consumeRecordsTotal > 0" :total="consumeRecordsTotal"
        :page.sync="consumeRecordsParams.pageNum" :limit.sync="consumeRecordsParams.pageSize"
        @pagination="getConsumeRecordsList" :page-sizes="[10, 20, 30, 50, 500, 1000]" />
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { getListAPI as getSiteListAPI } from "@/api/charge/site";
import {
  getListAPI,
  addOrUpdateAPI,
  deleteAPI,
  rechargeAPI,
  updateStatusAPI,
  getRechargeRecordsListAPI,
  getConsumeRecordsListAPI,
} from "@/api/charge/card";
import { exportExcel, exportExcelFromAPI } from "@/utils/utils";

export default {
  name: "Role",
  dicts: ["sys_normal_disable"],
  data() {
    return {
      moment,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],

      cardStatusMap: {
        ACTIVATED: "已激活",
        TO_BE_ACTIVATED: "待激活",
        LOSS: "已挂失",
        LOGOUT: "已注销",
      },

      cardTypeMap: {
        MONEY: "消费卡",
        NUMBER: "次数卡",
      },

      expireTypeMap: {
        LONG_TERM: "长期有效",
        SHORT_TERM: "短期有效",
      },

      optType: {
        RECHARGE: "小程序充值",
        MERCHANT_RECHARGE: "后台代充",
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cardNo: "",
      },
      // 表单参数
      form: {},

      // 表单校验
      rules: {
        // phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
        cardType: [
          { required: true, message: "请选择卡类型", trigger: "change" },
        ],
        expireType: [
          { required: true, message: "请选择有效期类型", trigger: "change" },
        ],
        expireTime: [
          { required: true, message: "请选择有效期", trigger: "change" },
        ],
      },

      statusVisible: false,
      rechargeVisible: false,
      rechargeRecordsVisible: false,
      consumeRecordsVisible: false,

      rechargeForm: {},
      rechargeRules: {
        balance: [
          { required: true, message: "请输入次数/金额(元)", trigger: "blur" },
        ],
      },

      statusForm: {},
      statusRules: {
        cardStatus: [
          { required: true, message: "请选择卡状态", trigger: "change" },
        ],
      },

      // 充值记录相关
      rechargeRecordsParams: {
        pageNum: 1,
        pageSize: 10,
        cardNo: "",
      },
      rechargeRecordsLoading: false,
      rechargeRecordsTotal: 0,
      rechargeRecordsList: [],

      // 消费记录相关
      consumeRecordsParams: {
        pageNum: 1,
        pageSize: 10,
        cardNo: "",
      },
      consumeRecordsLoading: false,
      consumeRecordsTotal: 0,
      consumeRecordsList: [],

      siteList: [],
    };
  },
  created() {
    this.getList();
    this.getSiteList();
  },
  methods: {
    exportData() {
      exportExcelFromAPI("/wallet/card/list/export", {
        ...this.queryParams,
        pageNum: 1,
        pageSize: 10000,
      });
      return false;
      exportExcel({
        data: this.formatTableList(this.list),
        headers: [
          { label: "id", key: "id" },
          { label: "编号", key: "cardNo" },
          { label: "手机号", key: "phone" },
          { label: "实体卡类型", key: "cardType" },
          { label: "余额(元)", key: "balance" },
          { label: "状态", key: "cardStatus" },
          { label: "备注", key: "remarks" },
          { label: "有效期类型", key: "expireType" },
          { label: "有效期", key: "expireTime" },
          { label: "创建时间", key: "createTime" },
        ],
        filename: "实体卡数据.xlsx",
      });
    },
    // 格式化表格数据
    formatTableList(data) {
      return data.map((item) => {
        return {
          ...item,
          balance: item.balance / 100,
          cardType: this.cardTypeMap[item.cardType],
          cardStatus: this.cardStatusMap[item.cardStatus],
          expireType: this.expireTypeMap[item.expireType],
          expireTime: this.parseTime(item.expireTime),
          createTime: this.parseTime(item.createTime),
        };
      });
    },
    // 查询全部站点
    getSiteList() {
      getSiteListAPI({
        pageNum: "1",
        pageSize: "500",
      }).then((res) => {
        this.siteList = res.rows.map((item) => {
          return {
            key: item.id,
            label: item.siteName,
          };
        });
      });
    },
    // 展示充值弹窗
    showRechargeModal(item) {
      this.rechargeForm = {
        id: item.id,
        balance: 0,
      };
      this.resetForm("rechargeForm");
      this.rechargeVisible = true;
    },
    // 展示修改状态弹窗
    showStatusModal(item) {
      this.statusForm = {
        id: item.id,
        cardStatus: "",
      };
      this.resetForm("statusForm");
      this.statusVisible = true;
    },
    // 展示充值记录弹窗
    showRechargeRecordsModal(item) {
      this.rechargeRecordsParams.cardNo = item.cardNo;
      this.getRechargeRecordsList(0);
      this.rechargeRecordsVisible = true;
    },
    // 展示消费记录弹窗
    showConsumeRecordsModal(item) {
      this.consumeRecordsParams.cardNo = item.cardNo;
      this.getConsumeRecordsList(0);
      this.consumeRecordsVisible = true;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getListAPI(this.queryParams).then((res) => {
        this.list = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 查询充值记录列表 */
    getRechargeRecordsList() {
      this.rechargeRecordsLoading = true;
      getRechargeRecordsListAPI(this.rechargeRecordsParams).then((res) => {
        this.rechargeRecordsList = res.rows;
        this.rechargeRecordsTotal = res.total;
        this.rechargeRecordsLoading = false;
      });
    },
    /** 查询充值记录列表 */
    getConsumeRecordsList() {
      this.consumeRecordsLoading = true;
      getConsumeRecordsListAPI(this.consumeRecordsParams).then((res) => {
        this.consumeRecordsList = res.rows;
        this.consumeRecordsTotal = res.total;
        this.consumeRecordsLoading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实体卡";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form = {
        id: row.id || "",
        phone: row.phone || "",
        cardType: row.cardType || "",
        expireType: row.expireType || "",
        cardNo: row.cardNo || "",
        balance: row.balance ? row.balance / 100 : "",
        remarks: row.remarks || "",
        crossSite: row.crossSite || "OFF",
      };
      if (row.expireType === "SHORT_TERM") {
        this.form.expireTime = new Date(moment(row.expireTime).valueOf());
      } else {
        this.form.expireTime = "";
      }
      if (row.crossSite === "ON") {
        this.$set(
          this.form,
          "siteIds",
          row.siteIds ? JSON.parse(row.siteIds) : []
        );
      } else {
        this.$set(this.form, "siteIds", []);
      }
      this.open = true;
      this.title = "修改实体卡";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          let params = { ...this.form };
          params.balance = params.balance * 100;

          // 短期有效期
          if (params.expireType === "SHORT_TERM") {
            params.expireTime = moment(params.expireTime).format(
              "YYYY-MM-DD 00:00:00"
            );
          } else {
            params.expireTime = "";
          }

          // 跨站站点
          if (params.crossSite === "ON") {
            params.siteIds = JSON.stringify(params.siteIds);
          } else {
            params.siteIds = JSON.stringify([]);
          }

          addOrUpdateAPI(params).then((res) => {
            if (this.form.id) {
              this.$modal.msgSuccess("修改成功");
            } else {
              this.$modal.msgSuccess("新增成功");
            }
            this.open = false;
            this.getList();
          });
        }
      });
    },
    // 充值表单提交
    submitRechargeForm() {
      this.$refs["rechargeForm"].validate((valid) => {
        if (valid) {
          rechargeAPI({
            id: this.rechargeForm.id,
            balance: this.rechargeForm.balance * 100, // 单位为元
          }).then((res) => {
            this.$modal.msgSuccess("充值成功");
            this.rechargeVisible = false;
            this.getList();
          });
        }
      });
    },
    // 修改状态表单提交
    submitStatusForm() {
      this.$refs["statusForm"].validate((valid) => {
        if (valid) {
          updateStatusAPI(this.statusForm).then((res) => {
            this.$modal.msgSuccess("状态修改成功");
            this.statusVisible = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm("确认删除吗？")
        .then(function () {
          return deleteAPI([row.id]);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
  },
};
</script>
